<?php

namespace App\Handlers;

use App\Models\AppleComments;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Readers\LaravelExcelReader;
use Mockery\Exception;

class ImportHandler
{

    public static function import(\Illuminate\Http\Request $request, $table, $fields = [], $checkedFields = [])
    {
        $file = $request->file('file');
        if (!$file->isValid()) {
            return [false, '上传失败'];
        }
        if (!in_array($file->getMimeType(), ['application/vnd.ms-office', 'application/vnd.ms-excel'])) {
            return [false, '请上传xls文件'];
        }

        try {
            $results = [];
            $added_amount = 0;
            $updated_amount = 0;
            $total_amount = 0;
            Excel::load($file->getRealPath(), function (LaravelExcelReader $reader)
            use (&$results, $fields, $checkedFields, $table, &$added_amount, &$updated_amount, &$total_amount) {
                $results = $reader->toArray();
                $total_amount = count($results);
                foreach ($results as $key => $data) {
                    $data = array_only($data, array_keys($fields));
                    $results[$key] = $data;
                    if ($checkedFields) {
                        $obj = DB::table($table)->where(function ($query) use ($checkedFields, $data, $key) {
                            foreach ($checkedFields as $checkedField) {
                                if (empty($data[$checkedField])) throw new Exception("第" . ($key + 2) . "行数据错误");
                                $query->where($checkedField, $data[$checkedField]);
                            }
                        })->first();
                        if ($obj) {
                            $data = array_filter($data);
                            DB::table($table)->where(function ($query) use ($checkedFields, $data) {
                                foreach ($checkedFields as $checkedField) {
                                    $query->where($checkedField, $data[$checkedField]);
                                }
                            })->limit(1)->update($data);
                            $updated_amount++;
                            unset($results[$key]);
                        }
                    }
                    if (empty($results[$key])) unset($results[$key]);
                }
                $chunks = array_chunk($results, 100);
                foreach ($chunks as $chunk) {
                    DB::table($table)->insert($chunk);
                }
                $added_amount = count($results);
            });
        } catch (Exception $exception) {
            throw $exception;
        }
        return [true, "总共{$total_amount}条,新增{$added_amount}条,更新{$updated_amount}条"];
    }

}